package me.sealer.demo;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

/**
 * Created by sealer on 17/05/15.
 */
public class MyClassLoader extends ClassLoader {
    //类加载器的名称
    private String name;

    //加载类的路径
    private String path = "G:/classes/";

    //文件类型
    private final String fileType = ".class";

    public MyClassLoader(String name) {
        super();
        this.name = name;
    }

    public MyClassLoader(ClassLoader parent, String name) {
        super(parent);
        this.name = name;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    @Override
    public String toString() {
        return this.name;
    }

    /**
     * 获取class的字节数组
     */
    public byte[] loadClassByteArray(String name) {
        InputStream is = null;
        byte[] bytes = null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        name = name.replace(".", "/");
        try {
            is = new FileInputStream(new File(path + name + fileType));
            int c = 0;
            while (-1 != (c = is.read())) {
                baos.write(c);
            }

            bytes = baos.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
                baos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return bytes;
    }

    /**
     * 获取class对象
     */
    @Override
    public Class<?> findClass(String name) {

        byte[] data = null;
        Class clazz = null;
        try {
            data = loadClassByteArray(name);
            clazz = this.defineClass(name, data, 0, data.length);
        } catch (Exception e) {
//            e.printStackTrace();
        }

        return clazz;
    }

    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        MyClassLoader loader1 = new MyClassLoader("loader1");
        loader1.setPath("D:/lib1/");

        MyClassLoader loader2 = new MyClassLoader(loader1, "loader2");
        loader2.setPath("D:/lib2/");

        MyClassLoader loader3 = new MyClassLoader(null, "loader3");
        loader3.setPath("D:/lib3/");

        Class clazz1 = loader1.loadClass("com.sealer.Sample");
        Object obj1 = clazz1.newInstance();

        /*Class clazz2 = loader2.loadClass("com.sealer.Sample");
        Object obj2 = clazz2.newInstance();*/

        /*Class clazz3 = loader3.loadClass("com.sealer.Sample");
        Object obj3 = clazz3.newInstance();*/

        /*System.out.println(clazz2.equals(clazz));*/


    }
}
